#!/bin/bash

set -eo pipefail
shopt -s inherit_errexit nullglob

# update bpmn-js version in the <bpmn.io> project

PWD="$(pwd)"
WORKDIR="$(pwd)/tmp"
CLONE_DIR="$WORKDIR/bpmn.io"

# create work dir
mkdir -p "$WORKDIR"

git clone --depth=1 "https://$BPMN_IO_TOKEN@github.com/bpmn-io/bpmn.io.git" "$CLONE_DIR"

cd "$CLONE_DIR"

PUBLISHED=`date +"%F %H:%M"`

echo "Updating toolkit version to version=$TAG, published=$PUBLISHED on bpmn.io"

cat src/data/site.yml | \
  tr "\r?\n" "\r" | \
  sed -e "s#bpmnjs:\r  version: [^\r]*\r  published: [^\r]*\r#bpmnjs:\r  version: $TAG\r  published: $PUBLISHED\r#" | \
  tr "\r" "\n" > src/data/site.yml_new

mv -f src/data/site.yml_new src/data/site.yml

if [[ "x$SKIP_COMMIT" = "x" ]]; then

  git config user.email "$BPMN_IO_EMAIL"
  git config user.name "$BPMN_IO_USERNAME"
  git config push.default simple

  # add all resources
  git add -A
  git commit -m "deps: bump bpmn-js to $TAG"
  git push -q &2>/dev/null
else
  echo "Skipping commit (SKIP_COMMIT=$SKIP_COMMIT)"
fi

cd "$PWD"